# coding=utf-8
from django import forms
from django.forms.utils import ValidationError
from django.utils.translation import ugettext_lazy as _

from task.models import TaskBase
from people.models import User, UserPrivate

from models import TradeTask


class TaskTradeForm(forms.ModelForm):
    trade_num = forms.CharField(max_length=255)
    task = forms.ModelChoiceField(queryset=TaskBase.objects.all(), required=True)
    pay_user = forms.ModelChoiceField(queryset=User.objects.all(), required=True)
    pay_way = forms.IntegerField(required=True)
    fare = forms.FloatField(required=True)
    station = forms.IntegerField(required=True)

    class Meta:
        model = TradeTask
        fields = [
            'task', 'pay_user', 'pay_way', 'remark',
            'station', 'fare', 'trade_num'
        ]


class PayTradeForm(forms.ModelForm):
    fare = forms.FloatField(required=True)
    pay_way = forms.IntegerField(required=True)
    pay_user = forms.ModelChoiceField(User.objects.all(), required=True)
    station = forms.IntegerField(required=True)

    class Meta:
        model = TradeTask
        fields = [
            'pay_way', 'station'
        ]

    def clean(self):
        cleaned_data = super(PayTradeForm, self).clean()

        # 判断支付金额是否正确
        if cleaned_data.get('fare') != self.instance.fare:
            self.add_error('fare', ValidationError(_('fare'), code='fare_error'))
        # 判断用户资产是否足够
        pay_user = cleaned_data.get('pay_user')
        pay_user_account = UserPrivate.objects.get(user_id=pay_user.pk)
        if pay_user_account.cash < cleaned_data.get('fare'):
            self.add_error('pay_user', ValidationError(_('pay_user'), code='cash_error'))

        return cleaned_data
